<template>
  <h1>Ref全家桶</h1>
  <p>ref: {{ man }}</p>
  <p>shallowRef: {{ man2 }}</p>
  <p>isRef: {{ flag }}</p>
  <p>customRef: {{ man3 }}</p>
  <div ref="dom">ref元素</div>
  <button @click="change">确定</button>
</template>

<script setup lang='ts'>
import { ref, shallowRef, triggerRef, customRef, isRef } from "vue";

/**
 * ref 全量响应式
 * shallowRef 浅度响应式
 * triggerRef 触发视图更新
 * customRef 自定义Ref
 */

const man = ref({
  name: "孙小双",
});

const man2 = shallowRef({
  name: "华天晓",
});

const flag = isRef(man);

function MyRef<T>(value: T) {
  let timer: any;
  return customRef((track, trigger) => ({
    get() {
      track();
      return value;
    },
    set(newValue: T) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        console.log('触发了')
        value = newValue;
        trigger();
      }, 500);
    },
  }));
}
const man3 = MyRef('刘备')

let dom = ref<HTMLDivElement>()


const change = () => {
  // man.value.name = '孙远杰'
  // man2.value.name = '李怡然'
  // triggerRef(man2)

  // man3.value = '曹操'

  if (dom.value) dom.value.innerText = '孙权'
}
</script>

<style lang='scss' scoped>
</style>